<?php

class DataGrid
{

    private $columnCount = "";
    private $template = '
		<style>
			.ui-datepicker-trigger{vertical-align:middle}
			.read-only{padding:5px !important; margin-right:5px !important;}
			#content a{color:#0E509E !important}
		</style>
		<div style="float: right; margin: 5px 0px;">{{MENU}}</div>
		<table class="GridTable" style="margin-top:10px; clear:both; width:100%">{{HEADER}}{{DATA}}</table>
	';
    private $menu = '';
    private $header = '';
    private $data = '';
    private $clickAction = '';
    private $pagination = '';
    private $exportButtonVisibility = false;
    private $actionColumnVisibility = true;
    private $columnsAlign = array();
    private $headerColumnsAlign = array();
    private $menuVisibility = true;
    private $actionColumnsWidth = 150;
    private $rowStyle = "GridItem1";
    private $infoRow = false;
    private $cellType = "td";

    function __construct()
    {
        
    }

    function addMenu($menu)
    {
        $this->menu .= $menu;
    }

    function addRowAction($action, $cssClass, $title)
    {
        $this->rowAction .= "<a id='" . mt_rand(1000, 10000) . "' href=\"#\" class=\"$cssClass\" title=\"$title\" onclick=\"javascript:$action\">&nbsp;</a>";
    }
    
    function addCustomRowAction($id, $action, $cssClass, $title)
    {
        $this->rowAction .= "<a id='$id' class=\"$cssClass\" title=\"$title\" onclick=\"javascript:$action\">$title</a>";
    }

    function setColumns()
    {
        $this->columnCount = func_num_args();
        $arguments = func_get_args();
        $this->setColumnsFromArray($arguments);
    }
    
    function setColumnsFromArray($arguments = array()){
        
        $this->header .= '<thead><tr class="GridHeader">';

        $rowColums = '';

        $counter = 0;

        foreach ($arguments as $argument)
        {
            $columnWidth = "";
            $columnAlign = "";
            $title = $argument;
            
            if(preg_match("#::#i", $argument))
            {
                $argument = explode("::", $argument);
                $title = $argument[0];
                $columnWidth = isset($argument[1])?"; width : " . $argument[1] . "px":"";
                $columnAlign = isset($argument[2])?"text-align : " . $argument[2]:"";
                $columnId = isset($argument[3])?"id=\"" . $argument[3] ."\"":"";
            }
            
            $rowColums .= '
                <'.$this->cellType.' style="' . ($columnAlign != "" ? $columnAlign : (isset($this->headerColumnsAlign[$counter])?"text-align : " . $this->headerColumnsAlign[$counter]:"")) . ' ' . $columnWidth . '" '.$columnId.'>' . ucwords($title) . '</'.$this->cellType.'>
            ';
            
            $counter++;
        }
        
        if ($this->actionColumnVisibility)
        {
            $rowColums .= '
                <td style="text-align:center; width:' . $this->actionColumnsWidth . 'px">Actions</td>
            ';
        }

        $this->header .= $rowColums;

        $this->header .= '</tr></thead>';
    }
    
    function setColumnsAlign()
    {
        $this->columnsAlign = func_get_args();
    }

    function setHeaderColumnsAlign()
    {
        $this->headerColumnsAlign = func_get_args();
    }
    
    function addEmptyRow($messsage = "&nbsp;")
    {
        $this->data .= '<tr class="GridItem2"><td colspan="' . ($this->columnCount + 1) . '" style="text-align:center">' . $messsage . '</td></tr>';
    }

    function addRowData()
    {
        $arguments = func_get_args();
        
        $this->addRowDataFromArray($arguments);
    }
    
    function addRowDataFromArray($arguments = array())
    {
        $this->data .= '<tr class="' . $this->rowStyle . '">';

        $counter = 0;
        foreach ($arguments as $argument)
        {
            $cellAction = "";

            if (!preg_match("#:NONROWACTION#", $argument))
            {
                $cellAction = ' onclick="javascript:' . $this->clickAction . '"';
            }
            else
            {
                $argument = preg_replace("#:NONROWACTION#", "", $argument);
            }

            $this->data .= '
				<td style="text-align:' . (isset($this->columnsAlign[$counter]) ? $this->columnsAlign[$counter] : "left") . '" ' . $cellAction . '>' . ucwords($argument) . '</td>
			';
            $counter++;
        }

        if ($this->actionColumnVisibility)
        {
            $this->data .= '<td style="text-align:center; padding:5px 0px">' . $this->rowAction . '</td>';
        }

        $this->rowAction = '';

        $this->data .= "</tr>";
        
        if($this->infoRow)
        {
            $this->data .= "<tr style='display:none'><td style='padding:10px' colspan='" . ($this->columnCount + 1) . "'>Hello world</td></tr>";
        }
    }

    function setPaginationData($totalData = 0, $itemPerPage = 20, $uri = '', $rowCount = 0, $result_count = 0)
    {
        if ($rowCount > 0 && $result_count > $itemPerPage)
        {
            $CI = &get_instance();
            $CI->load->library('pagination');

            $config['base_url'] = base_url() . "index.php/" . $uri . "?" . $_SERVER["QUERY_STRING"];
            $config['total_rows'] = $totalData!= 0?$totalData:$result_count;
            $config['per_page'] = $itemPerPage;
            $config['page_query_string'] = true;
            $config['first_link'] = '&laquo; First ';
            $config['last_link'] = '<strong>Last &raquo; </strong>';
            $config['next_link'] = '<strong>Next &raquo; </strong>';
            $config['prev_link'] = '&laquo; Prev';

            $config['num_tag_open'] = '<span style="padding:0px 5px; border-right:1px solid #ccc">';

            $config['num_tag_close'] = '</span>';

            $CI->pagination->initialize($config);

            $this->pagination = '<center style="margin:10px 0px; font-size:10px; color:#000 !important;"><div style="width:100%; padding:5px">' . $CI->pagination->create_links() . '</div></center>';
        }
    }

    function setPaginationDataNew($totalData = 0, $itemPerPage = 20, $uri = '', $rowCount = 0, $offset = 0)
    {
        if ($rowCount > 0 && $totalData >= ($offset + $itemPerPage))
        {
            $CI = &get_instance();
            $CI->load->library('pagination');

            $config['base_url'] = base_url() . "index.php/" . $uri . "?" . preg_replace("#&per_page=[0-9]+#i", "", $_SERVER["QUERY_STRING"]);
            $config['total_rows'] = (($offset + $itemPerPage) != ($offset + $rowCount)) ? ($offset + $rowCount) : $totalData;
            $config['per_page'] = $itemPerPage;
            $config['page_query_string'] = true;
            $config['first_link'] = '&laquo; First ';
            $config['last_link'] = '<strong>Last &raquo; </strong>';
            $config['next_link'] = '<strong>Next &raquo; </strong>';
            $config['prev_link'] = '&laquo; Prev';

            $config['num_tag_open'] = '<span style="padding:0px 5px; border-right:1px solid #ccc">';

            $config['num_tag_close'] = '</span>';

            $CI->pagination->initialize($config);

            $this->pagination = '<center style="margin:10px 0px; font-size:10px; color:#000 !important;"><div style="width:100%; padding:5px">' . $CI->pagination->create_links() . '</div></center>';
        }
    }

    function setEmptyDataState($messsage = "")
    {
        $this->data = '<tr class="GridItem1"><td colspan="' . ($this->columnCount + 1) . '" style="text-align:center">' . $messsage . '</td></tr>';
    }

    function render($to_string = false)
    {
        $CI = &get_instance();

        if ($this->exportButtonVisibility)
        {
            $data['buttonExport'] = $CI->exportLastQuery();
        }
        else
        {
            $data = array();
        }

        if ($this->menuVisibility)
        {
            $this->menu .= $CI->load->view('template/header_menu', $data, true);
        }
        else
        {
            $this->menu .= "";
        }
        
        $result = str_ireplace(array("{{MENU}}", "{{HEADER}}", "{{DATA}}"), array($this->menu, $this->header, "<tbody>".$this->data."</tbody>"), $this->template) . $this->pagination;
        
        if(!$to_string)
            echo $result;
        else
            return $result;
    }

    function setButtonExportVisible($visible = true)
    {
        $this->exportButtonVisibility = $visible;
    }

    function setActionColumnVisible($visible = true)
    {
        $this->actionColumnVisibility = $visible;
    }

    function setMenuVisible($visible = true)
    {
        $this->menuVisibility = $visible;
    }

    function setActionColumnsWidth($width)
    {
        $this->actionColumnsWidth = $width;
    }

    function onRowClickAction($clickAction = "")
    {
        $this->clickAction = $clickAction;
    }

    function setRowStyle($rowStyle = "")
    {
        $this->rowStyle = $rowStyle;
    }
    
    function setInfoRow($infoRow = false)
    {
        $this->infoRow = $infoRow;
    }
    
    function setCellType($cell = 'td')
    {
        $this->cellType = $cell;
    }
    
}

?>